/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nhncorp.neptune.client;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.nhncorp.neptune.neptune_test.common.NeptuneClusterTestCase;
import com.nhncorp.neptune.tablet.TableSchema;
import com.nhncorp.neptune.tablet.TabletInfo;

/**
 * NTable의 기본 기능에 대한 테스트
 * 
 * @author nhn
 * 
 */
public class TestNTable extends NeptuneClusterTestCase {
  private static final int numTabletServers = 3;

  public TestNTable(String name) {
    super(name, true, numTabletServers);
  }

  public void testClientCache() throws Exception {
    System.out.println("================================= testClientCache =================================");
    String[] rowKeyStr = { "1000", "2000", "3000" };

    Row.Key[] rowKeys = new Row.Key[rowKeyStr.length + 1];

    for (int i = 0; i < rowKeyStr.length; i++) {
      rowKeys[i] = new Row.Key(rowKeyStr[i]);
    }
    rowKeys[rowKeyStr.length] = Row.Key.MAX_KEY;

    TableSchema tableInfo = makeTestTableInfo();
    NTable.createTable(conf, tableInfo, rowKeys);
    NTable ntable = NTable.openTable(conf, tableInfo.getTableName());

    TabletLocationCache cache = TabletLocationCache.getInstance(conf);
    TabletInfo tabletInfo = cache.lookupUserTablet(ntable.getTableName(),
        new Row.Key("0001"));

    assertNotNull(tabletInfo);
    assertEquals("1000", tabletInfo.getEndRowKey().toString());

    assertEquals(2, cache.rootCache.size());
    assertEquals(8, cache.metaCache.size());

    // insert
    String data = "1234567890";
    for (int i = 0; i < 10; i++) {
      data += data;
    }
    DecimalFormat df = new DecimalFormat("0000");
    for (int i = 0; i < 4000; i++) {
      Row row =  new Row(new Row.Key(df.format(i)));
      row.addCell(tableInfo.getColumn(0), new Cell(new Cell.Key("1"), data.getBytes()));
      ntable.put(row);
    }

    assertEquals(8, cache.metaCache.size());

    // split 후 테스트
    TabletInfo[] tabletInfos = ntable.listTabletInfos();
    int beforeSize = tabletInfos.length;
    NTableManager.connectTabletManager(tabletInfos[0].getAssignedHostName(),
        conf).doActionForTest(tabletInfos[0].getTabletName(), "split");

    while (true) {
      tabletInfos = ntable.listTabletInfos();
      if (tabletInfos.length == beforeSize + 1) {
        break;
      }
      Thread.sleep(1000);
    }

    Row.Key findRowKey = new Row.Key("0001");
    // TabletInfo oldTabletInfo = cache.findFromCache(cache.metaCache,
    // findRowKey);
    TabletInfo afterTabletInfo = cache.lookupUserTablet(ntable.getTableName(),
        findRowKey);

    assertNotNull(afterTabletInfo);
    // cache에 이는 내용이 삭제되지 않았기 때문에 이전과 동일해야 한다.
    assertEquals(tabletInfo, afterTabletInfo);

    int beforeCacheSize = cache.metaCache.size();
    // cache에서 삭제 처리한다.
    cache.clearTabletCache(ntable.getTableName(), findRowKey, afterTabletInfo);

    // 삭제 여부 확인
    assertEquals(beforeCacheSize - 2, cache.metaCache.size());

    // cache에서 찾지 못한다.
    assertNull(cache.findFromCache(cache.metaCache, findRowKey));

    // cache miss가 나고 찾아 온다.
    afterTabletInfo = cache.lookupUserTablet(ntable.getTableName(), findRowKey);

    assertNotNull(afterTabletInfo);

    assertTrue(afterTabletInfo.getEndRowKey().compareTo(findRowKey) >= 0);

    // 실제 데이터를 조회해본다.
    cache.clearAllCache();

    Row row = ntable.get(findRowKey, tableInfo.getColumnsArray());
    assertNotNull(row);
    assertEquals(findRowKey, row.getKey());
  }

  /**
   * GRID-11 서로 다른 JVM 내에서 테이블 scnema를 변경했을 때 변경된 정보를 정상적으로 가져오는지 테스트
   * 
   * @throws IOException
   */
  
  public void testTableSchemaChanged() throws IOException {
    TableSchema tableInfo = makeTestTable("T_UPLOAD_TEST");

    NTable.createTable(conf, tableInfo);

    NTable ntable1 = NTable.openTable(conf, tableInfo.getTableName());
    NTable ntable2 = NTable.openTable(conf, tableInfo.getTableName());

    TableSchema tableInfo1 = ntable1.descTable();
    TableSchema tableInfo2 = ntable2.descTable();
    assertTrue(Arrays.equals(tableInfo1.getColumnsArray(), tableInfo2
        .getColumnsArray()));

    ntable1.addColumn("ADD_TEST1");

    tableInfo1 = ntable1.descTable();
    assertEquals(tableInfo.getColumnsArray().length + 1, tableInfo1
        .getColumnsArray().length);
    tableInfo2 = ntable2.descTable();

    assertTrue(Arrays.equals(tableInfo1.getColumnsArray(), tableInfo2
        .getColumnsArray()));
  }
  
  /*
  public void testGetThread() throws Exception {
    TableInfo tableInfo = makeTestTable("T_GET");

    NTable.createTable(conf, tableInfo);

    NTable ntable = NTable.openTable(conf, tableInfo.getTableName());

    for (int i = 0; i < 1000; i++) {
      Row.Key rowKey = new Row.Key(df.format(i));
      // ntable.startTx(rowKey);
      ColumnValue columnValue = new ColumnValue(rowKey, new Cell.Key(df
          .format(i)), null);
      ColumnValue[][] values = new ColumnValue[2][];
      values[0] = new ColumnValue[] { columnValue };
      values[1] = new ColumnValue[] { columnValue };

      ntable.insertRow(rowKey, tableInfo.getColumnsArray(), values);
      // ntable.commit();
    }

    List<Row.Key> rowKeys = new ArrayList<Row.Key>();
    for (int i = 0; i < 100; i++) {
      rowKeys.add(new Row.Key(df.format(i)));
    }

    TestReceiver receiver = new TestReceiver();

    ntable.get(rowKeys, tableInfo.getColumnsArray(), receiver, 10, 10 * 1000);

    while (true) {
      Thread.sleep(50);
      if (receiver.end) {
        break;
      }
    }

    if (receiver.exception != null) {
      throw receiver.exception;
    }

    assertEquals(rowKeys.size(), receiver.result.size());
  }
*/
  static class TestReceiver implements AsyncDataReceiver {
    private boolean end = false;
    private Exception exception;
    private List<Row.Key> result = new ArrayList<Row.Key>();
    private List<Row> resultValues = new ArrayList<Row>();

    @Override
    public void error(Row.Key rowKey, Exception exception) {
      end = true;
      this.exception = exception;
    }

    @Override
    public void receive(Row.Key rowKey, Row row)
        throws IOException {
      result.add(rowKey);
      resultValues.add(row);
    }

    @Override
    public void timeout() {
      // TODO Auto-generated method stub
      
    }
  }
}
